<?php


	//returns distance between two gps locations
	function distance($lat1, $lon1, $lat2, $lon2) { 
		$theta = $lon1 - $lon2; 
		$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
		$dist = acos($dist); 
		$dist = rad2deg($dist); 
		$miles = $dist * 60 * 1.1515;

		return $miles;	
	}
	
	//gets address based on gps location
	function GetGps($loc){
		$loc=str_replace(' ','%20',$loc);
		$xml = file_get_contents('http://maps.googleapis.com/maps/api/geocode/xml?address='.$loc.'&sensor=false');
		preg_match('/<lat>(.*?)<\/lat>/', $xml, $lats);
		preg_match('/<lng>(.*?)<\/lng>/', $xml, $lons);
		return $lats[1].','.$lons[1];
	}
	
	//Returns all places matching the general location search within 1 mile (1609 meters)
	function Genloc($genloc, $gps){
		$pieces = explode(",",$gps);
		$lat=$pieces[0];
		$lon=$pieces[1];
		
		$genloc=str_replace(' ','%20',$genloc);
		$xml = file_get_contents('https://maps.googleapis.com/maps/api/place/search/xml?location='.$gps.'&radius=1609&keyword='.$genloc.'&sensor=false&key=AIzaSyBTowK1H74MGGnNfffCLmaITz1zcvMFSWc');
		
		preg_match_all('/<name>(.*?)<\/name>/', $xml, $names);
		preg_match_all('/<lat>(.*?)<\/lat>/', $xml, $lats);
		preg_match_all('/<lng>(.*?)<\/lng>/', $xml, $lons);
		
		$count=0;
		$dist=array();

		//finds the distances
		foreach($names[0] as $value){
			$dist[$count] = Distance($lats[1][$count], $lons[1][$count], $lat, $lon);
			$count++;
		}
		
		//sorts the array based on distance
		array_multisort($dist,$names[1],$lats[1],$lons[1]);
		
		$count=0;
		
		foreach ($names[1] as $value){
			echo str_replace(':','::',$value).':';
			echo str_replace(':','::',$lats[1][$count]).',';
			echo str_replace(':','::',$lons[1][$count]).':';
			$count++;
		}	
	}
	
	//returns all terms matching the specific location entered
	function Specloc($loc){
		$gps = GetGps($loc);
		$loc=str_replace(' ','%20',$loc);
		$xml = file_get_contents('http://maps.googleapis.com/maps/api/geocode/xml?address='.$loc.'&sensor=false');
		preg_match_all('/<formatted_address>(.*?)<\/formatted_address>/', $xml, $names);
		preg_match_all('/<lat>(.*?)<\/lat>/', $xml, $lats);
		preg_match_all('/<lng>(.*?)<\/lng>/', $xml, $lons);
		$count=0;
		
		foreach ($names[1] as $value){
			echo str_replace(':','::',$value).':';
			echo str_replace(':','::',$lats[1][$count]).',';
			echo str_replace(':','::',$lons[1][$count]).':';
			$count++;
		}	
		
	}
	
	//returns all the reminders for a given user
	function Check(&$username, &$password){
		// Make a MySQL Connection
		mysql_connect("localhost", "***", "***") or die(mysql_error());
		mysql_select_db("***") or die(mysql_error());
		
		$result = mysql_query("SELECT * FROM Users_table where username='$username'") or die(mysql_error());  
		$row = mysql_fetch_array( $result );

		if ($row['password'] == $password){
			$uid = $row['user_id'];
			$result = mysql_query("SELECT * FROM Reminders_table where user_id='$uid'")
			or die(mysql_error());  
			
			//prints out the data, changing all ":" to "::"
			while ($row = mysql_fetch_array( $result )){
				$temp = (string)$row['reminder_title'];
				echo str_replace(":","::",$temp);
				echo ":";
				$temp = (string)$row['reminder_text'];
				echo str_replace(":","::",$temp);
				echo ":";
				echo $row['reminder_id'];
				echo ":";
				if ($row['time_boolean']){
					echo date('Y-m-d H::i::s',$row['reminder_time']);
					echo ":";
				}
				if (!$row['time_boolean']){
					echo 0;
					echo ":";
				}
				if($row['general_location']!=NULL){
					echo $row['general_location'].':';
				}
				else{
					echo ' :';
				}
				if($row['address']!=NULL){
					echo str_replace(":","::",$row['address'].":".$row['coordinates']);
				}
				else {
					echo ' ';
				}
				echo ' :';
				
			}
		}

		else{
			echo "Incorrect password";
		}
	}
	
	//registers a new user
	function Register(&$username, &$password, &$email){
		// Make a MySQL Connection
		mysql_connect("localhost", "***", "***") or die(mysql_error());
		mysql_select_db("***") or die(mysql_error());
		mysql_query("INSERT INTO Users_table (username, password, email)
		VALUES ('$username', '$password', '$email')");
		
		if(1 === mysql_affected_rows())
			echo 'registered';
		else
			echo 'duplicate username';
	}
	
	//edits a reminder
	function Edit(&$reminderid, &$username, &$password, &$title, &$reminder, &$remindertime, &$genloc, &$specloc){
		mysql_connect("localhost", "***", "***") or die(mysql_error());
		mysql_select_db("***") or die(mysql_error());
		
		$result = mysql_query("SELECT * FROM Users_table where username='$username'") or die(mysql_error());  
		$row = mysql_fetch_array( $result );
		
		if ($remindertime != NULL){
			$remindertime = strtotime( $remindertime);
			$timebool = 1;
		}
		if ($remindertime == NULL){
			$timebool = 0;
			$remindertime = "000-00-00 00:00:00";
			$remindertime = strtotime( $remindertime);
		}
			
		if ($specloc != NULL)
		{
			$gps=GetGps($specloc);
		}
		
		if ($row['password'] == $password){
			$uid = $row['user_id'];
			mysql_query("UPDATE Reminders_table SET reminder_title='$title', reminder_text='$reminder', time_boolean='$timebool',reminder_time='$remindertime', general_location='$genloc', coordinates='$gps',address='$specloc' WHERE reminder_id='$reminderid'");
			if(1 === mysql_affected_rows()){
				echo(1);
			}
			else{
				echo 'error editing';
			}
		}
		if ($row['password'] != $password){
			echo "Incorrect password";
		}
		
		
	}
	
	//adds a reminder
	function Add(&$username, &$password, &$title, &$reminder, &$remindertime, &$genloc, &$specloc){
		mysql_connect("localhost", "***", "***") or die(mysql_error());
		mysql_select_db("***") or die(mysql_error());
		
		$result = mysql_query("SELECT * FROM Users_table where username='$username'") or die(mysql_error());  
		$row = mysql_fetch_array( $result );
		

		if ($remindertime != NULL){
			$remindertime = strtotime( $remindertime);
			$timebool = 1;
		}
		if ($remindertime == NULL){
			$timebool = 0;
			$remindertime = "000-00-00 00:00:00";
			$remindertime = strtotime( $remindertime);
		}
		
		
		if ($specloc != NULL)
		{
			$gps=GetGps($specloc);
		}
		
		echo $specloc;
		echo "<br>";
		echo $gps;
		if ($row['password'] == $password){
			$uid = $row['user_id'];
			mysql_query("INSERT INTO Reminders_table (reminder_title, reminder_text, user_id, time_boolean, reminder_time, general_location, coordinates, address)
			VALUES ('$title', '$reminder','$uid','$timebool','$remindertime','$genloc','$gps','$specloc')");
			if(1 === mysql_affected_rows()){
				echo(mysql_insert_id());
			}
			else{
				echo 'error adding';
			}
		}
		if ($row['password'] != $password){
			echo "Incorrect password";
		}
	
	}
	
	//removes the reminder with the corresponding ID
	function Remove(&$username, &$password, &$reminderid){
		mysql_connect("localhost", "***", "***") or die(mysql_error());
		mysql_select_db("***") or die(mysql_error());
		
		$result = mysql_query("SELECT * FROM Users_table where username='$username'") or die(mysql_error());  
		$row = mysql_fetch_array( $result );
		
		if ($row['password'] == $password){
			mysql_query("DELETE FROM Reminders_table WHERE reminder_id='$reminderid'");
			if(1 === mysql_affected_rows())
				echo 'removed';
			else
				echo 'error removing';
		}
		else{
			echo "Incorrect password";
		}
	}
	
	//checks if the login credentials are valid
	function Login(&$username, &$password){
		mysql_connect("localhost", "***", "***") or die(mysql_error());
		mysql_select_db("***") or die(mysql_error());
		
		$result = mysql_query("SELECT * FROM Users_table where username='$username'") or die(mysql_error());  
		$row = mysql_fetch_array( $result );
		
		if ($row['password'] == $password){
			return 1;
		}
		if ($row['password'] != $password){
			return 0;
		}
	}


	
	
	
	
	//					//
	//					//
	// CODE STARTS HERE	//
	//					//
	//					//
	
	
	
	//pulls variables from url
	$action = $_GET["action"];
	$genloc = $_GET["genloc"];
	$email = $_GET["email"];
	$gengps = $_GET["gengps"];
	$password = md5($_GET["password"]);
	$reminder = $_GET["reminder"];
	$reminderid = $_GET["reminderid"];
	$remindertime = $_GET["remindertime"];
	$specloc = $_GET["specloc"];
	$title = $_GET["title"];
	$username = $_GET["username"];
	
	
	
	if ($username == NULL || $password == NULL || $action == NULL){
		die("Missing some variable");
	}

	
	//calls the corresponding function, based on what actions the android requested
	if ($action == 'edit'){
		if ($reminderid == NULL){
			die("Missing reminder id");
		}
		Edit($reminderid, $username, $password, $title, $reminder, $remindertime, $genloc, $specloc);
	}
	if ($action == 'genloc'){
		if ($genloc != NULL){
			Genloc($genloc,$gengps);
		}
	}
	if ($action == 'specloc'){
		if ($specloc != NULL){
			Specloc($specloc);
		}
	}
	if ($action == "check"){
		Check($username,$password);	
	}
	if ($action == "register"){
		if ($email == NULL){
			die("Missing Email");
		}
		Register($username,$password,$email);
	}
	if ($action == "add"){
		if ($title == NULL || $reminder == NULL){
			die("Missing info for reminder");
		}
		Add($username, $password, $title, $reminder, $remindertime, $genloc, $specloc);
	}
	if ($action == "remove"){
		if ($reminderid == NULL){
			die("Missing reminder id");
		}
		Remove($username,$password,$reminderid);
	}
	if ($action == "login"){
		echo Login($username,$password);
	}

?>